package com.example.graduatedesigned.adapter;

import static android.content.Context.NOTIFICATION_SERVICE;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.TextView;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.app.NotificationCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.example.graduatedesigned.MainActivity;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.example.graduatedesigned.R;
import com.example.graduatedesigned.bean.ItemBean;
import com.example.graduatedesigned.bean.LedProductRequest;
import com.example.graduatedesigned.deepseek.DeepSeekClient;
import com.example.graduatedesigned.deepseek.RequestMessageItem;
import com.example.graduatedesigned.http.ApiService;
import com.example.graduatedesigned.http.RetrofitClient;
import com.example.graduatedesigned.utils.DevicesInfo;
import com.example.graduatedesigned.bean.DataResponse;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class MainAdapter extends BaseMultiItemQuickAdapter<ItemBean, BaseViewHolder> {
    private String hotUnit;
    private String wetUnit;
    private String concentrationUnit;
    private int colorHot;
    private int colorNormal;
    private int colorWet;
    private int colorAirMid;
    private int colorAirGood;
    private String text;
    private int color;
    private Context context;
    private long lastNotificationTime = 0;
    public MainAdapter(Context context) {
        this.context = context;
        addItemType(ItemBean.TYPE_NORMAL, R.layout.normal_item);
        addItemType(ItemBean.TYPE_SWITCH, R.layout.switch_item);
    }

    // 提前获取资源 getContext() Please get it after onAttachedToRecyclerView()
    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        hotUnit = getContext().getString(R.string.hot_unit);
        wetUnit = getContext().getString(R.string.wet_unit);
        concentrationUnit = getContext().getString(R.string.concentration_unit);
        colorHot = getContext().getColor(R.color.hot);
        colorNormal = getContext().getColor(R.color.black);
        colorWet = getContext().getColor(R.color.wet);
        colorAirMid = getContext().getColor(R.color.air_mid);
        colorAirGood = getContext().getColor(R.color.air_good);
    }

    @Override
    protected void convert(@NonNull BaseViewHolder helper, ItemBean itemBean) {
        switch (itemBean.getItemType()) {
            case com.example.graduatedesigned.bean.ItemBean.TYPE_NORMAL:
                TextView tv = helper.getView(R.id.mainParams);
                getTextParams(itemBean.getText(), itemBean.getTitle());
                tv.setText(text);
                tv.setTextColor(color);
                helper.setText(R.id.mainTitle, itemBean.getTitle());
                Glide.with(getContext())
                        .load(itemBean.getIcon())
                        .into((ImageView) helper.getView(R.id.mainImg));
                break;
            case com.example.graduatedesigned.bean.ItemBean.TYPE_SWITCH:
                SwitchCompat switchCompat = helper.getView(R.id.mainSwitch);
                switchCompat.setChecked(itemBean.isChecked());
                helper.setText(R.id.mainTitle, itemBean.getTitle());
                Glide.with(getContext())
                        .load(itemBean.getIcon())
                        .into((ImageView) helper.getView(R.id.mainImg));
                break;
        }
    }

    private void getTextParams(String params, String title) {
        switch (title) {
            case "温度":
                text = String.format(hotUnit, params);
                if (Float.parseFloat(params) >= 30f) {
                    color = colorHot;
                    sendNotification(title, text);
                    showLed(true);
                } else {
                    color = colorNormal;
                    showLed(false);
                }
                break;
            case "湿度":
                text = String.format(wetUnit, params);
                if (Float.parseFloat(params) >= 50f) {
                    color = colorWet;
                    sendNotification(title, text);
//                    showLed(true);
                } else {
                    color = colorNormal;
//                    showLed(false);
                }
                break;
            case "设备状态":
                text = params;
                if (params.equals("离线")) {
                    color = colorHot;
                } else {
                    color = colorAirGood;
                }
                break;
        }
    }

    private void sendNotification(String title, String text) {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastNotificationTime >= 30000) {
            DeepSeekClient deepSeekClient = new DeepSeekClient();
            List<RequestMessageItem> requestMessageItemList = new ArrayList<>();
            String tips = "当前" + title + "是" + text;
            requestMessageItemList.add(new RequestMessageItem("user",  tips+ ",请给出10个字以内的简短的建议"));
            deepSeekClient.ask(requestMessageItemList, false, new DeepSeekClient.Lis() {
                @Override
                public void msg(String msg) {
                    Intent intent = new Intent(context, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
                    NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
                    NotificationChannel channel = new NotificationChannel("MingZ", "Graduate Designed",
                            NotificationManager.IMPORTANCE_HIGH);
                    nm.createNotificationChannel(channel);
                    Notification notification = new NotificationCompat.Builder(context, "MingZ")
                            .setContentTitle("异常警报")
                            .setContentIntent(pendingIntent)
                            .setContentText(tips + "，建议：" + deepSeekClient.getMsg(msg))
                            .setSmallIcon(R.drawable.ic_notification)
                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_notifiation_big))   //设置大图标
                            .build();
                    nm.notify(1, notification);
                    lastNotificationTime = currentTime; // 更新最后发送通知的时间
                }
            });
        }
    }

    private void showLed(Boolean checked) {
        ApiService service = RetrofitClient.getInstance();
        String productId = DevicesInfo.product_id;
        String deviceName = DevicesInfo.device_name;
        LedProductRequest.Params params = new LedProductRequest.Params(checked);
        LedProductRequest productRequest = new LedProductRequest(productId, deviceName, params);
        Call<DataResponse> call = service.setLedDeviceStatus(DevicesInfo.auth_info, productRequest);
        call.enqueue(new Callback<DataResponse>() {
            @Override
            public void onResponse(Call<DataResponse> call, Response<DataResponse> response) {
            }

            @Override
            public void onFailure(Call<DataResponse> call, Throwable t) {
                Log.d("joidajodas", t.toString());
            }
        });
    }
}
